package Matter;

import Form.LNode;

public class Link {
    public LNode root;

    public Link() {
        this.root = null;
    }

    public Link(LNode root) {
        this.root = root;
    }

    public Link(String preOrder, String inOrder, int preIndex, int inIndex, int count) {
        if (count > 0) {
            char r = preOrder.charAt(preIndex);
            int i = 0;
            for (; i < count; i++)
                if (r == inOrder.charAt(i + inIndex))
                    break;
            root = new LNode(r);
            root.lchild = new Link(preOrder, inOrder, preIndex + 1, inIndex, i).root;
            root.rchild = new Link(preOrder, inOrder, preIndex + i + 1, inIndex + i + 1, count - i - 1).root;
        }
    }

    private static int index=0;
    //以先序遍历创建二叉树
    public  Link(String preStr) {
        char c = preStr.charAt(index++);
        if (c != '#') {
            root = new LNode(c);
            root.lchild = new Link(preStr).root;
            root.rchild = new Link(preStr).root;
        } else
            root = null;
    }
    //先序遍历
    public void preRootTraverse(LNode T) {
        if (T != null) {
            System.out.print(T.data);
            preRootTraverse(T.lchild);
            preRootTraverse(T.rchild);
        }
    }

    //中序遍历
    public void inRootTraverse(LNode T) {
        if (T != null) {
            inRootTraverse(T.lchild);
            System.out.print(T.data);
            inRootTraverse(T.rchild);
        }
    }

    //后序遍历
    public void postRootTraverse(LNode T) {
        if (T != null) {
            postRootTraverse(T.lchild);
            postRootTraverse(T.rchild);
            System.out.print(T.data);
        }
    }

    //层次遍历
    public void levelTraverse() {
        LNode T = root;
        if (T != null) {
            LinkQueue L = new LinkQueue();
            L.offer(T);
            while (!L.isEmpty()) {
                T = (LNode) L.poll();
                System.out.print(T.data);
                if (T.lchild != null) ;
                L.offer(T.lchild);
                if (T.rchild != null)
                    L.offer(T.rchild);
            }
        }
    }

    public LNode getRoot() {
        return root;
    }

    public void setRoot(LNode root) {
        this.root = root;
    }

    //删除子树
    public void delete(Object no) {
        if (root != null) {
            if (root.data == no) {
                root = null;
            } else {
                root.delete(no);
            }
        } else {
            System.out.println("二叉树为空");
        }
    }

    //添加子树
    public void insert(Object roo,Link dat) {
       if(root!=null){
            if (root.data==roo){
                root.insert(roo,dat);
            }else {
                root.insert(roo,dat);
            }
       }else{
           root=dat.root;
       }
    }
}


